<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Twitter Hook
 *
 * PHP version 5
 * LICENSE: This source file is subject to AGPL license 
 * that is available through the world-wide-web at the following URI:
 * http://www.gnu.org/licenses/agpl.html
 * @author	   Omar Vega Ramos <ovruni@gnu.org.pe> 
 * @copyright      (c) 2013 - 2016 Omar Vega Ramos
 * @license	   http://www.gnu.org/licenses/agpl.html GNU Affero General Public License (AGPL) 
 */

class twitter {
  
  protected $consumer_key;
  protected $consumer_secret;
  protected $oauth_token;
  protected $oauth_token_secret;
  
  /**
   * Registers the main event add method
   */
  public function __construct()
  {
    // Hook into routing
    Event::add('system.pre_controller', array($this, 'add'));
    
    // Retrieve Current Settings
    $twitter = ORM::factory('twitter', 1);
    
    // Setting variables
    $this->consumer_key = $twitter->consumer_key;
    $this->consumer_secret = $twitter->consumer_secret;
    $this->oauth_token = $twitter->oauth_token;
    $this->oauth_token_secret = $twitter->oauth_token_secret;
  }
  
  /**
   * Adds all the events to the main Ushahidi application
   */
  public function add()
  {
    if (($this->oauth_token == '') OR ($this->oauth_token_secret == ''))
      return;
    
    // Only add the events if we are on that controller
    if (Router::$controller == 'reports' AND Router::$method == 'index') {
      Event::add('ushahidi_action.report_approve', array($this, 'post_twitter'));
    }
    
    if (Router::$controller == 'reports' AND Router::$method == 'edit') {
      Event::add('ushahidi_action.report_edit', array($this, 'post_twitter'));
    }
  }
  
  public function post_twitter()
  {
    // Access the report approved
    $post = Event::$data;
    
    if ($post->incident_active == 1) {
      $title = trim($post->incident_title);
      $url = url::site('reports/view/'.$post->id);
      $status = ($title != '') ? $title.': '.$url : $url;
      
      $params = array();
      
      $params['status'] = $status;
      
      $client = new Oauth_client_class;
      $client->oauth_version = '1.0a';
      $client->url_parameters = FALSE;
      $client->authorization_header = TRUE;
      $client->access_token = $this->oauth_token;
      $client->access_token_secret = $this->oauth_token_secret;
      $client->client_id = $this->consumer_key;
      $client->client_secret = $this->consumer_secret;
      
      $success = $client->CallAPI(
				  'https://api.twitter.com/1.1/statuses/update.json',
				  'POST',
				  $params,
				  array(
					'FailOnAccessError' => TRUE,
					),
				  $update
				  );
    }
  }
}

new twitter;
